<%@ Page Language="C#" %>
<%@ Import Namespace="BLF.WWW_WWW.Wiki" %>
<%@ Import Namespace="Model.WWW_WWW.Wiki" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (SessionFacade.LoginKey == null && Settings.PrivateAccess)
        {
            Response.Redirect("AccessDenied.htm");
        }

        if (Request["File"] == null)
        {
            Response.Write(Exchanger.ResourceExchanger.GetResource("FileNotFound"));
            return;
        }

        string filename = Settings.UploadDirectory + Request["File"];
        DirectoryInfo info = new DirectoryInfo(Path.GetDirectoryName(filename).TrimEnd('\\'));
        DirectoryInfo up = new DirectoryInfo(Settings.UploadDirectory.TrimEnd('\\'));
        if (!info.FullName.ToLower().StartsWith(up.FullName.ToLower()))
        {
            Response.Write(filename + "<br />");
            Response.Write(Exchanger.ResourceExchanger.GetResource("Forbidden"));
            return;
        }
        if (!File.Exists(filename))
        {
            Response.Write(filename + "<br />");
            Response.Write(Exchanger.ResourceExchanger.GetResource("FileNotFound"));
            return;
        }

        string mime = "";
        try
        {
            string ext = Path.GetExtension(filename);
            if (ext.StartsWith(".")) ext = ext.Substring(1).ToLower(); // Remove trailing dot
            mime = GetMimeType(ext);
        }
        catch
        {
            Response.Write(filename + "<br />");
            Response.Write(Exchanger.ResourceExchanger.GetResource("FileNotFound"));
            //mime = "application/octet-stream";
            return;
        }

        Response.Clear();
        Response.AddHeader("content-type", mime);
        Response.AddHeader("content-disposition", "inline;filename=\"" + Path.GetFileName(filename) + "\"");
        Response.WriteFile(filename);

    }

    private string GetMimeType(string ext)
    {
        string mime = "";
        if (MimeTypes.Types.TryGetValue(ext, out mime)) return mime;
        else return "application/octet-stream";
    }
</script>